package com.phkj.qdh.utils

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Matrix
import com.phkj.qdh.App
import java.io.*
import java.text.SimpleDateFormat
import java.util.*


object TakePhoto {


    //保存处理后的图片，并且返回本地的url
    fun saveBitmap2File(bm: Bitmap?): String {
        val simpleDate = SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault())
        val fileName = simpleDate.format(GregorianCalendar().time) + ".jpg"
        val myCaptureFile = File(App.CONTEXT.externalCacheDir, fileName)
        var bos: BufferedOutputStream? = null
        try {
            bos = BufferedOutputStream(FileOutputStream(myCaptureFile))
            bm?.compress(Bitmap.CompressFormat.PNG, 100, bos)
            bos.flush()
            bos.close()
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return myCaptureFile.absolutePath
    }

    //图片压缩处理
    fun scaleBitmap(origin: Bitmap?,ratio:Float): Bitmap? {
        if (origin == null) {
            return null
        }
        val width = origin.width
        val height = origin.height
        val matrix = Matrix()
        matrix.preScale(ratio, ratio)
        //旋转图片
        matrix.postRotate(0.0f)
        val newBM = Bitmap.createBitmap(origin, 0, 0, width, height, matrix, false)
        if (newBM == origin) {
            return newBM
        }
        origin.recycle()
        return newBM
    }

    //压缩图片
    private fun compressImage(image: Bitmap?): Bitmap? {
        if (image == null) {
            return null
        }
        val baos = ByteArrayOutputStream()
        image.compress(Bitmap.CompressFormat.JPEG, 100, baos)//质量压缩方法，这里100表示不压缩，把压缩后的数据存放到baos中
        var options = 100
        while (baos.toByteArray().size / 1024 > 1024) {    //循环判断如果压缩后图片是否大于100kb,大于继续压缩
            baos.reset()//重置baos即清空baos
            options -= 30//每次都减少10
            image.compress(Bitmap.CompressFormat.JPEG, options, baos)//这里压缩options%，把压缩后的数据存放到baos中
            LogUtil.E("压缩一次——————————————————————————————————————————————————")
        }
        val isBm = ByteArrayInputStream(baos.toByteArray())//把压缩后的数据baos存放到ByteArrayInputStream中
        return BitmapFactory.decodeStream(isBm, null, null)//把ByteArrayInputStream数据生成图片
    }

    fun zhiliang(bitmap: Bitmap,quality:Int): Bitmap {
        val outputStream = ByteArrayOutputStream()
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
        val bytes = outputStream.toByteArray();
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.size)
    }


    fun getRandomString(): String {
        val sb = StringBuilder()
        val str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        val random = Random()
        for (i in 1..4) {
            val index = random.nextInt(62)
            sb.append(str.toCharArray()[index])
        }

        return sb.toString()
    }
}
